package com.akupilih.app;

import org.afree.data.general.DefaultPieDataset;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.akupilih.app.chart.PieChartView;
import com.akupilih.app.helper.VolleyHelper;
import com.akupilih.app.model.WebService;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class VoteChartFragment extends Fragment {
	private String URL;
	private String TAG = "Hasil Voting";
	private FragmentActivity myContext;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		URL = WebService.VOTE_RESULT();
		PieChartView view = getData(myContext, URL);
		return view;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		myContext = (FragmentActivity) activity;

	}

	private PieChartView getData(final Context contex, String URL) {
		final DefaultPieDataset dataset = new DefaultPieDataset();
		JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
				URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject obj) {

						try {

							JSONObject root = obj.getJSONObject("total");
							for (int i = 1; i <= root.length(); i++) {
								JSONObject job = root.getJSONObject(i + "");
								dataset.setValue(job.getString("candidate"),
										job.getInt("hasil"));
							}

						} catch (JSONException e) {
							ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
									+ e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						ACRAPostSender.TRACE(TAG
								+ ".getData(...).new ErrorListener() {...}",
								"onErrorResponse : " + error.toString());
						VolleyHelper.showVolleyError(contex, error);
					}
				});
		BaseApplication.getInstance().addToRequestQueue(request, TAG);
		PieChartView chart = new PieChartView(contex, dataset, TAG);
		return chart;
	}

}
